package com.threadlocal.demo;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: ThreadLocalMemoryLeak
 * @Description: ThreadLocal内存泄露demo
 * @Author: PAUL XUE
 * @Date: 2022/1/13 3:20 PM
 * @Version: 1.0
 **/
public class ThreadLocalMemoryLeak {
    static class LocalVariable {
        private Long[] a = new Long[1024 * 1024];
    }

    //    (1)
    final static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 5, 1, TimeUnit.MINUTES, new LinkedBlockingQueue<>());
    //    (2)
    final static ThreadLocal<LocalVariable> localVariable = new ThreadLocal<>();

    public static void main(String[] args) {
        //(3)
        try {
            Thread.sleep(5000 * 4);
            for (int i = 0; i < 50; i++) {
                poolExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        //    (4)
                        localVariable.set(new LocalVariable());
                        //    (5)
                        System.out.println("use local variable" + localVariable.get());
                    }
                });
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("pool execute over");
    }
}
